import { SetupContext, computed, ref, toRefs } from 'vue'
import { InputEmit, InputProps } from '../input-types'

export default function (props: InputProps, ctx: SetupContext<InputEmit>) {
  const { type } = toRefs(props)
  const textType = computed(() => (props.type ? (props.type === 'password' ? pwdType.value : props.type) : 'text'))
  const pwdType = ref('password')
  const isDisabled = computed(() => !!props.disabled)
  const isReadonly = computed(() => !!props.readonly)
  const rounded = computed(() => (props.round ? props.round + 'px' : ''))
  const width = computed(() => (typeof props.width === 'number' ? props.width + 'px' : props.width))
  const placeholder = computed(() => (props.placeholder ? props.placeholder : '请输入内容'))
  const textInput = computed({
    get: () => props.modelValue,
    set: (val) => {
      ctx.emit('update:modelValue', val)
    }
  })
  const handleInput = (event: Event) => {
    let { value } = event.target as HTMLInputElement
    textInput.value = value
  }
  const handleFocus = (event: Event) => {
    ctx.emit('focus', event)
  }
  const handleBlur = (event: Event) => {
    ctx.emit('blur', event)
  }
  const handleChange = (event: Event) => {
    let { value } = event.target as HTMLInputElement
    ctx.emit('change', value)
  }
  const handleKeydown = (event: Event) => {
    ctx.emit('keydown', event)
  }
  const changeType = () => {
    if (pwdType.value === 'password') {
      pwdType.value = 'text'
    } else {
      pwdType.value = 'password'
    }
  }
  return {
    type,
    width,
    textType,
    pwdType,
    isDisabled,
    isReadonly,
    rounded,
    placeholder,
    textInput,
    handleInput,
    handleFocus,
    handleBlur,
    handleChange,
    handleKeydown,
    changeType
  }
}
